package com.hz.tgb.id.snow;

import com.hz.tgb.common.RandomUtil;
import com.hz.tgb.datetime.DateUtil;

import java.util.Date;

/**获取生成随机的订单号
 *
 * @author hezhao
 */
public class GenerateOrderNoUtil {

    private static final String name = "LOAN";

    /***
     * 获取指定长度的订单号(推荐订单号27位)
     * @param length
     * @return
     */
    public static String getOrderNo(int length) {
        String result = "";
        if (length <= 0) {
            return result;
        }
        Snowflake snowFlake = SnowflakeUtils.getInstance(0, length, name);
        // 雪花算法生成的随机id
        long snowRandowmId = snowFlake.nextId();
        String snowRandowmIdStr = String.valueOf(snowRandowmId);
        int randomLength = snowRandowmIdStr.length();
        if (length < randomLength) {
            result = RandomUtil.getRandomNumByUuid(length);
        } else {
            int paddingLen = length - randomLength;
            result = paddingStr(snowRandowmIdStr, '0', paddingLen);
        }

        return result;
    }

    /***
     * 获取指定长度含日期的订单号(推荐订单号27位)
     * @param length
     * @return
     */
    public static String getOrderNoWithDate(int length){
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
        String randomStr = getOrderNo(length - 8);
        return dateStr + randomStr;
    }

    /***
     * 填充指定长度的字符串,右填充
     *
     * @param source
     * @param c
     * @param paddingLen
     * @return
     */
    private static String paddingStr(String source, char c, int paddingLen) {
        StringBuilder sb = new StringBuilder(source);
        for (int i = 0; i < paddingLen; i++) {
            sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(GenerateOrderNoUtil.getOrderNo(27));
    }
}


